package com.dup.jxlh.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dup.jxlh.admin.entities.model.ChapterApply;
import com.dup.jxlh.admin.entities.vo.ChapterApplyVO;
import com.dup.jxlh.admin.mapper.ChapterApplyMapper;
import com.dup.jxlh.admin.service.ChapterApplyService;
import com.dup.jxlh.admin.service.OwnValidatorService;
import com.dup.jxlh.api.entities.PaginationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;

@Service("chapterApplyServiceImpl")
public class ChapterApplyServiceImpl implements ChapterApplyService {
    @Resource
    private ChapterApplyMapper chapterApplyMapper;

    @Autowired
    private OwnValidatorService ownValidatorService;

    @Override
    @Cacheable(value = "chapterapply", key = "#id")
    public ChapterApply getChapterApply(BigInteger id) {
        return chapterApplyMapper.selectById(id);
    }

    @Override
    public Page<ChapterApplyVO> getChapterApplyList(PaginationData paginationData, ChapterApply chapterApply) {
        Page<ChapterApplyVO> page = new Page<>(paginationData.getCurrent(), paginationData.getSize());
        page.setOptimizeCountSql(false);
        QueryWrapper<ChapterApply> queryWrapper = new QueryWrapper<>();

        ownValidatorService.setChapterQueryWrapperByLevel(queryWrapper, paginationData);

        if (!paginationData.getSearch().isEmpty()) {
            queryWrapper.and(i -> i
                    .like("name", paginationData.getSearch())
                    .or()
                    .like("code", paginationData.getSearch()));
        }

        if (chapterApply.getDepartmentId() != null) {
            queryWrapper.eq("department_id", chapterApply.getDepartmentId());
        }

        if (chapterApply.getType() != null) {
            queryWrapper.eq("type", chapterApply.getType());
        }

        if (chapterApply.getStatus() != null) {
            queryWrapper.eq("status", chapterApply.getStatus());
        }

        ArrayList<ChapterApplyVO> list = chapterApplyMapper.getChapterApplyList(page, queryWrapper);
        page.setRecords(list);
        return page;
    }
}
